services:
  setup:
    image: {{ nexus_docker_proxy | default('docker.elastic.co') }}elasticsearch/elasticsearch:{{ elk.version }}
    volumes:
      - {{ elk.deploy_path }}/config/certs:/usr/share/elasticsearch/config/certs
    container_name: elasticsearch-setup
    user: "0"
    command: >
      bash -c '
        if [ x${ELASTIC_PASSWORD} == x ]; then
          echo "Set the ELASTIC_PASSWORD environment variable in the .env file";
          exit 1;
        elif [ x${KIBANA_PASSWORD} == x ]; then
          echo "Set the KIBANA_PASSWORD environment variable in the .env file";
          exit 1;
        fi;
        if [ ! -f config/certs/ca.zip ]; then
          echo "Creating CA";
          bin/elasticsearch-certutil ca --silent --pem -out config/certs/ca.zip;
          unzip config/certs/ca.zip -d config/certs;
        fi;
        if [ ! -f config/certs/certs.zip ]; then
          echo "Creating certs";
          echo -ne \
          "instances:\n"\
{% for node in groups['es_cluster'] %}
          "  - name: es-{{ hostvars[node]['inventory_hostname'] | replace('.', '-') }}\n"\
          "    dns:\n"\
          "      - es-{{ hostvars[node]['inventory_hostname'] | replace('.', '-') }}\n"\
          "      - localhost\n"\
          "    ip:\n"\
          "      - {{ hostvars[node]['ansible_host'] | default(hostvars[node]['inventory_hostname']) }}\n"\
{% endfor %}
          > config/certs/instances.yml;
          bin/elasticsearch-certutil cert --silent --pem -out config/certs/certs.zip --in config/certs/instances.yml --ca-cert config/certs/ca/ca.crt --ca-key config/certs/ca/ca.key;
          unzip config/certs/certs.zip -d config/certs;
        fi;
        echo "Setting file permissions"
        chown -R root:root config/certs;
        find . -type d -exec chmod 750 \{\} \;;
        find . -type f -exec chmod 640 \{\} \;;
        echo "Waiting for Elasticsearch availability";
        until curl -s --cacert config/certs/ca/ca.crt https://{{ es_node_name }}:9200 | grep -q "missing authentication credentials"; do sleep 30; done;
        echo "Setting kibana_system password";
        until curl -s -X POST --cacert config/certs/ca/ca.crt -u "elastic:${ELASTIC_PASSWORD}" -H "Content-Type: application/json" https://{{ es_node_name }}:9200/_security/user/kibana_system/_password -d "{\"password\":\"${KIBANA_PASSWORD}\"}" | grep -q "^{}"; do sleep 10; done;
        echo "All done!";
      '
    healthcheck:
      test: ["CMD-SHELL", "[ -f config/certs/{{ es_node_name }}/{{ es_node_name }}.crt ]"]
      interval: 1s
      timeout: 5s
      retries: 120